package com.ihrm.system.service;

import com.ihrm.common.service.BaseService;
import com.ihrm.common.utils.IdWorker;
import com.ihrm.common.utils.PermissionConstants;
import com.ihrm.domain.system.Permission;
import com.ihrm.domain.system.Role;
import com.ihrm.domain.system.User;
import com.ihrm.system.dao.PermissionDao;
import com.ihrm.system.dao.RoleDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

@Service
public class RoleService extends BaseService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    /**
     * 添加角色
     *
     * @param role
     */
    public void save(Role role) {
        // 填充参数
        role.setId(idWorker.nextId() + "");
        roleDao.save(role);
    }

    /**
     * 更新角色
     *
     * @param role
     */
    public void update(Role role) {
        Role target = roleDao.getOne(role.getId());
        target.setDescription(role.getDescription());
        target.setName(role.getName());
        roleDao.save(target);
    }


    /**
     * 根据id查询角色
     *
     * @param id
     * @return
     */
    public Role findById(String id) {
        return roleDao.findById(id).get();
    }

    public List<Role> findAll(String companyId) {
        return roleDao.findAll(getSpecification(companyId));
    }

    /**
     * 根据id删除角色
     *
     * @param id
     */
    public void delete(String id) {
        roleDao.deleteById(id);
    }

    /**
     * 分页查询角色
     *
     * @param map
     * @param page
     * @param size
     * @return
     */
    public Page<Role> findSearch(Map<String, Object> map, int page, int size) {
        Specification<Role> specification = new Specification<Role>() {
            @Override
            public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<>();
                //根据请求的companyId是否为空构造查询条件
                if (!StringUtils.isEmpty(map.get("companyId"))) {
                    list.add(criteriaBuilder.equal(root.get("companyId").as(String.class), (String) map.get("companyId")));
                }
                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        };
        //2.分页
        Page<Role> pageRole = roleDao.findAll(specification, new PageRequest(page - 1, size));
        return pageRole;
    }

    public Page<Role> findByPage(String companyId, int page, int size) {
        return roleDao.findAll(getSpecification(companyId), PageRequest.of(page - 1, size));
    }

    // 分配权限
    public void assignPerms(String roleId, List<String> permIds) {
        // 1 获取分配的角色对象
        Role role = roleDao.findById(roleId).get();
        // 2 构造角色的权限集合
        Set<Permission> perms = new HashSet<>();
        for (String permId:permIds) {
            Permission permission = permissionDao.findById(permId).get();
            // 需要根据父ID和类型查询API权限列表
            List<Permission> apiList = permissionDao.findByTypeAndPid(PermissionConstants.PERMISSION_API,permission.getPid());
            perms.addAll(apiList);//自定赋予API权限
            perms.add(permission);//当前菜单或按钮的权限
        }
        System.out.println(perms.size());
        // 3 设置角色和权限的关系
        role.setPermissions(perms);
        // 4 更新角色
        roleDao.save(role);
    }
}
